﻿#include "SIX_GlobalMgr.h"

bool SIX_GlobalMgr::m_bAlreadyDeleted = false;

void SIX_GlobalMgr::LoadMusic(const char *folder,const char *fName)
{
	if (!m_bInited)
		return;

	CCString oldFolder(CCFileUtils::sharedFileUtils()->getResourceDirectory());

	pMusicMgr->SetSoundResourceFolder(folder);
	CCFileUtils::sharedFileUtils()->setResourceDirectory(folder);
    
#if (CC_TARGET_PLATFORM==CC_PLATFORM_IOS)
    // 创建临时目录
    // Cool.Cat
    string tmpFolder("");
    tmpFolder.append(SIX_CCIOSHelper::GetInstance()->getAppPathTemporary());
    tmpFolder.append(folder);
    mkdir(tmpFolder.c_str(),S_IRWXU|S_IRWXG|S_IRWXO);
#endif

	int retv = pMusicMgr->LoadXMLFromFile(fName);
	if (retv!=0)
	{
        // 恢复原始的资源路径
        CCFileUtils::sharedFileUtils()->setResourceDirectory(oldFolder.getCString());
		SIXLog("LoadMusic[%s].Error[%d]",fName,retv);
		return;
	}
	pMusicMgr->ReleaseXML();

	// 恢复原始的资源路径
	CCFileUtils::sharedFileUtils()->setResourceDirectory(oldFolder.getCString());

	int total = pMusicMgr->GetTotalSoundCount();
	int soundCount = pMusicMgr->GetBgSoundCount();
	int effectCount = pMusicMgr->GetEffectSoundCount();

	SIXLog("Music.Total[%d].soundCount[%d].effectCount[%d]",total,soundCount,effectCount);
}

void SIX_GlobalMgr::StopAllMusicAndEffect()
{
	if (!m_bInited)
		return;

	pMusicMgr->stopAllEffects();
	pMusicMgr->stopBackgroundMusic();
}

void SIX_GlobalMgr::PlayNextBackgroundMusic()
{
	if (!m_bInited)
		return;

	// 随机背景音乐，且不为上次播放的音乐
	int soundCount = pMusicMgr->GetBgSoundCount();
	if (soundCount==0)
		return;
	int rnd = SIX_Utility::GetInstance()->RNDNUM(0,soundCount-1);
	int retry = 0;
	while (rnd==m_LastBackgroundMusicIdx && retry<3)
	{
		rnd = SIX_Utility::GetInstance()->RNDNUM(0,soundCount-1);
		retry++;
	}
	m_LastBackgroundMusicIdx = rnd;
	StopAllMusicAndEffect();
	pMusicMgr->playBackgroundMusic(m_LastBackgroundMusicIdx,true);
	SIXLog("Using BG[%d] Now!",m_LastBackgroundMusicIdx);
}

void SIX_GlobalMgr::PlayChangeSceneMusic()
{
	if (!m_bInited)
		return;

	StopAllMusicAndEffect();
	pMusicMgr->playEffect(22);
}

void SIX_GlobalMgr::ParseXML(SIX_DSTPL<SIX_XmlDataSet> *pXmlDataSet)
{
	if (!pMusicMgr)
		return;

	SIX_XmlDataSet *pDataSet = 0;

	//SIXLog("ParseXML.GetChildrenCount[%d]",pXmlDataSet->GetChildrenCount());
	CCARRAY_FOREACH_T(pXmlDataSet->GetChildren(),pDataSet,SIX_XmlDataSet*)
	{
		// 跳过Root和Comment
		if (STRCMP(pDataSet->getKey().c_str(),"Element"))
			continue;

		if (pDataSet->pDataElement)
		{
			if (!STRCMP(pDataSet->getValue().c_str(),"Volume"))
			{
				SIX_KV *pKV = 0;
				CCARRAY_FOREACH_T(pDataSet->pDataElement->GetChildren(),pKV,SIX_KV*)
				{
					if (!STRCMP(pKV->getKey().c_str(),"Background"))
					{
						float vol = (float)atof(pKV->getValue().c_str());
						if (vol<=0.0f)
							vol = 0.0f;
						if (vol>=1.0f)
							vol = 1.0f;
						pMusicMgr->m_BackgroundVolume = vol;
					}
					else if (!STRCMP(pKV->getKey().c_str(),"Effect"))
					{
						float vol = (float)atof(pKV->getValue().c_str());
						if (vol<=0.0f)
							vol = 0.0f;
						if (vol>=1.0f)
							vol = 1.0f;
						pMusicMgr->m_EffectVolume = vol;
					}
				}
			}
			else if (!STRCMP(pDataSet->getValue().c_str(),"LastLoginInfo"))
			{
				SIX_KV *pKV = 0;
				CCARRAY_FOREACH_T(pDataSet->pDataElement->GetChildren(),pKV,SIX_KV*)
				{
					// 上一次登录账户名
					if (!STRCMP(pKV->getKey().c_str(),"LastLoginName"))
					{
						this->SetLastLoginName(pKV->getValue().c_str());
					}
					// 上一次登录账户密码
					else if (!STRCMP(pKV->getKey().c_str(),"LastLoginPass"))
					{
						this->SetLastLoginPass(pKV->getValue().c_str());
					}
				}
			}
			else
			{
				SIX_KV *pKV = 0;
				map<string, map<string, string> >::iterator mNodeData = m_mReadWriteData.find(pDataSet->getValue().c_str());

				CCARRAY_FOREACH_T(pDataSet->pDataElement->GetChildren(), pKV, SIX_KV*)
				{
					if (m_mReadWriteData.end() == mNodeData)
					{
						map<string, string> tmpAttribute;
						tmpAttribute.insert(make_pair(pKV->getKey().c_str(), pKV->getValue().c_str()));
						m_mReadWriteData.insert(make_pair(pDataSet->getValue().c_str(), tmpAttribute));
						mNodeData = m_mReadWriteData.find(pDataSet->getValue().c_str());
					}
					else
					{
						map<string, string>::iterator mAttrite = mNodeData->second.find(pKV->getKey().c_str());
						if (mNodeData->second.end() == mAttrite)
							mNodeData->second.insert(make_pair(pKV->getKey().c_str(), pKV->getValue().c_str()));
						else
							mAttrite->second = pKV->getValue().c_str();
					}
				}
			} //end else
		}
	}
}

void SIX_GlobalMgr::LoadProfile(char *ProfPath)
{
	if (!m_bInited)
		return;

	// 音量
	if (pMusicMgr)
	{
		// 默认音量百分比50%
		// Cool.Cat
		pMusicMgr->m_BackgroundVolume = 0.5f;
		pMusicMgr->m_EffectVolume = 0.5f;

		string savePath(SIX_Utility::GetInstance()->GetAppBasePath(ProfPath));
#ifdef WIN32
		wstring ufolder(SIX_Utility::GetInstance()->Utf8ToUnicode(savePath.c_str()).c_str());
		CreateDirectory(ufolder.c_str(),0);
#else
		savePath.clear();
#if (CC_TARGET_PLATFORM==CC_PLATFORM_ANDROID)
		savePath.append(SIX_CCJNIHelper::GetInstance()->getReadWritePathJNI());
#else
		savePath.append(SIX_CCIOSHelper::GetInstance()->getAppPathDocment());
#endif
		savePath.append("/");
		savePath.append(ProfPath);
		mkdir(savePath.c_str(),S_IRWXU|S_IRWXG|S_IRWXO);
		savePath.append("/");
#endif

		this->SetLastLoginName("");
		this->SetLastLoginPass("");

		const char *proFile = CCString::createWithFormat("%sprof.dat",SIX_Utility::GetInstance()->U2G(savePath.c_str()).c_str())->getCString();
		//SIXLog("proFile=%s",proFile);

		unsigned long len = 0;
		bool isPopupNotify = CCFileUtils::sharedFileUtils()->isPopupNotify();
		CCFileUtils::sharedFileUtils()->setPopupNotify(false);
		unsigned char *pXMLData = CCFileUtils::sharedFileUtils()->getFileData(proFile,"rb",&len);
		CCFileUtils::sharedFileUtils()->setPopupNotify(isPopupNotify);
		if (!pXMLData || !len)
			return;

		SIX_XMLParser *pXML = new SIX_XMLParser();
		int retv = pXML->LoadXMLFromMemory(pXMLData,len);
		CC_SAFE_DELETE_ARRAY(pXMLData);
		if (retv==-1 || retv==-2)
		{
			WLOG("LoadProfile.Error!");
			CC_SAFE_DELETE(pXML);
			return;
		}

		ParseXML(pXML->GetXMLDataSet());
		pXML->ReleaseXMLDataSet();
		CC_SAFE_DELETE(pXML);
	}
}

void SIX_GlobalMgr::SaveProfile(char *ProfPath)
{
	if (!m_bInited)
		return;

	// 音量
	if (pMusicMgr)
	{
		string savePath(SIX_Utility::GetInstance()->GetAppBasePath(ProfPath));
#ifdef WIN32
		wstring ufolder(SIX_Utility::GetInstance()->Utf8ToUnicode(savePath.c_str()).c_str());
		CreateDirectory(ufolder.c_str(),0);
#else
		savePath.clear();
#if (CC_TARGET_PLATFORM==CC_PLATFORM_ANDROID)
		savePath.append(SIX_CCJNIHelper::GetInstance()->getReadWritePathJNI());
#else
		savePath.append(SIX_CCIOSHelper::GetInstance()->getAppPathDocment());
#endif
		savePath.append("/");
		savePath.append(ProfPath);
		mkdir(savePath.c_str(),S_IRWXU|S_IRWXG|S_IRWXO);
		savePath.append("/");
#endif

		TiXmlDocument *pDoc = new TiXmlDocument();
		TiXmlDeclaration* pDec = new TiXmlDeclaration("1.0","UTF-8","");
		pDoc->LinkEndChild(pDec);
		
		TiXmlElement *pRoot = new TiXmlElement("Profile");
		SYSTEMTIME st;
		SIX_Utility::GetInstance()->GetLocalTime(&st);
		CCString *timeNow = CCString::createWithFormat("%04d-%02d-%02d %02d:%02d:%02d %03d",
			st.wYear,st.wMonth,st.wDay,
			st.wHour,st.wMinute,st.wSecond,st.wMilliseconds);
		pRoot->SetAttribute("Update",timeNow->getCString());
		pDoc->LinkEndChild(pRoot);
		
		TiXmlElement *pNode = new TiXmlElement("Volume");
		pRoot->LinkEndChild(pNode);
		pNode->SetAttribute("Background",CCString::createWithFormat("%.2f",pMusicMgr->m_BackgroundVolume)->getCString());
		pNode->SetAttribute("Effect",CCString::createWithFormat("%.2f",pMusicMgr->m_EffectVolume)->getCString());
		
		TiXmlElement *pNode2 = new TiXmlElement("LastLoginInfo");
		pRoot->LinkEndChild(pNode2);
		if (strlen(this->GetLastLoginName()))
			pNode2->SetAttribute("LastLoginName",this->GetLastLoginName());
		if (strlen(this->GetLastLoginPass()))
			pNode2->SetAttribute("LastLoginPass",this->GetLastLoginPass());

		map<string, map<string, string> >::const_iterator mNodeData = m_mReadWriteData.begin();
		for (; mNodeData != m_mReadWriteData.end(); ++mNodeData)
		{
			TiXmlElement *pNode3 = new TiXmlElement(mNodeData->first.c_str());
			pRoot->LinkEndChild(pNode3);

			map<string, string>::const_iterator mAttrite = mNodeData->second.begin();
			for (; mAttrite != mNodeData->second.end(); ++mAttrite)
			{
				pNode3->SetAttribute(mAttrite->first.c_str(), mAttrite->second.c_str());
			}
		}

		const char *proFile = CCString::createWithFormat("%sprof.dat",SIX_Utility::GetInstance()->U2G(savePath.c_str()).c_str())->getCString();
		pDoc->SaveFile(proFile);
		pDoc->Clear();
		CC_SAFE_DELETE(pDoc);

		if (!CCFileUtils::sharedFileUtils()->getDecryptKeyLength())
			return;

		// 加密
		// Cool.Cat
		FILE *fp = fopen(proFile,"rb");
		if (!fp)
		{
			WLOG("SaveProfile.Error.A!");
			return;
		}
		fseek(fp,0,SEEK_END);
		long pSize = ftell(fp);
		fseek(fp,0,SEEK_SET);
		unsigned char *pBuffer = new unsigned char[pSize];
		if (fread(pBuffer,pSize,1,fp)!=1)
		{
			WLOG("SaveProfile.Error.B!");
			CC_SAFE_DELETE_ARRAY(pBuffer);
			fclose(fp);
			return;
		}
		fclose(fp);

		CCFileUtils::sharedFileUtils()->decryptStream(pBuffer,pSize);

		fp = fopen(proFile,"wb");
		if (!fp)
		{
			WLOG("SaveProfile.Error.C!");
			CC_SAFE_DELETE_ARRAY(pBuffer);
			return;
		}
		if (fwrite(pBuffer,pSize,1,fp)!=1)
		{
			WLOG("SaveProfile.Error.D!");
			CC_SAFE_DELETE_ARRAY(pBuffer);
			fclose(fp);
			return;
		}
		CC_SAFE_DELETE_ARRAY(pBuffer);
		fclose(fp);
	}
}

bool SIX_GlobalMgr::getProData(const string &strNodeName, const string &strAttributeName, string &strValue)
{
	map<string, map<string, string> >::const_iterator mNodeData = m_mReadWriteData.find(strNodeName);
	if (m_mReadWriteData.end() != mNodeData)
	{
		map<string, string>::const_iterator mAttribute = mNodeData->second.find(strAttributeName);
		if (mNodeData->second.end() != mAttribute)
		{
			strValue = mAttribute->second;
			return true;
		}
	}
	return false;
}

void SIX_GlobalMgr::setProData(const string &strNodeName, const string &strAttributeName, const string &strValue)
{
	map<string, map<string, string> >::iterator mNodeData = m_mReadWriteData.find(strNodeName);
	if (m_mReadWriteData.end() != mNodeData)
	{
		map<string, string>::iterator mAttribute = mNodeData->second.find(strAttributeName);
		if (mNodeData->second.end() != mAttribute)
			mAttribute->second = strValue;
		else
			mNodeData->second.insert(make_pair(strAttributeName, strValue));
	}
	else
	{
		map<string, string> tmpAttribute;
		tmpAttribute.insert(make_pair(strAttributeName, strValue));
		m_mReadWriteData.insert(make_pair(strNodeName, tmpAttribute));
	}
}

void SIX_GlobalMgr::UnZipAndDecryptFile()
{
	if (!m_bInited)
		return;

	if (!pFS)
		return;

//	// 解压目录
//	pFS->UnZipToFolder("iphonehd.zip");
//#ifdef WIN32
//	pFS->UnZipToFolder("Sound.zip");
//#else
//#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
//	pFS->UnZipToFolder("Music.zip");
//#endif
//#endif
}